/**
 * 
 */
package com.macbulldev.poc.testgin.service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;



import org.apache.log4j.Logger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import com.macbulldev.poc.testgin.domain.AppRole;
import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.PolicyType;
import com.macbulldev.poc.testgin.domain.Underwriter;

/**
 * @author solid
 *
 */
//@Component("autoInit")
public class AutoSetupService {
	private static final Logger LOGGER=Logger.getLogger(AutoSetupService.class);
	
	
	@Autowired
	@Qualifier("schedulerFactory")
	private SchedulerFactoryBean schedulerFactory;

	
	/**
	 * 
	 */
	
	public AutoSetupService() {
		
	}

	/**
	 * Go through the auto setup.properties and 
	 * configure the application when approperiate
	 */
	
	public synchronized void init(){

		
		try
		{
			Properties setupProps = new Properties();
			setupProps.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("setup.properties"));
			if (setupProps!=null && !setupProps.isEmpty() 
					&& setupProps.get("auto.configure")!=null 
					&& ((String)setupProps.get("auto.configure")).equals("true"))
			{
				LOGGER.debug(" Initting Admin Users ");
				List<String> roles=Arrays.asList(((String)setupProps.getProperty("admin.default.roles")).split(","));
				for (String role: roles)
				{
				
					List<AppUser> appAdmins = AppUser.findUsersByRole(role);
					if (appAdmins.size()==0)
					{
						String email =((String)setupProps.getProperty("admin.default.email")).trim();
						AppUser user=	AppUser.getByEmail(email);
						if (user==null)
						{
							user = new AppUser();
							user.setEmail(email);
							user.setPassword(((String)setupProps.getProperty("admin.default.password")).trim());
							user.setIsEnabled(true);
							user.setIsApproved(true);
							user.setPhoneNumber("(999)999-9999");
							user.setName(((String)setupProps.getProperty("admin.default.username")).trim());
						}
						user.addRole(role);
					    user.merge();
						
					}

				}
				List<String> availRoles=Arrays.asList(((String)setupProps.getProperty("roles.default.unassociated")).split(","));
				for (String role: availRoles)
				{
					
					role=role.trim();
					LOGGER.debug("Role="+role);
					List<AppRole> appRoles = AppRole.findUnassociatedRoleByRoleString(role);
					
					LOGGER.debug("searching for "+role+" yeilded "+appRoles.size()+" results");
					if (appRoles == null || appRoles.size()<1)
					{
						AppRole newRole = new AppRole();
						newRole.setRoleString(role);
						newRole.persist();
					}
					
				}
				
				List<String> uwList=Arrays.asList(((String)setupProps.getProperty("underwriters.default.displayname")).split(","));
				for (String uw: uwList)
				{
					String displayName = uw.split(":")[0];
					String importName = uw.split(":")[1];
					
					LOGGER.debug("Underwriter:  "+displayName+":"+importName);
					
					if(Underwriter.findUnderwriterByDisplayNameAndImportName(displayName, importName) == null || Underwriter.findUnderwriterByDisplayNameAndImportName(displayName, importName).size() == 0)
					{
						
						LOGGER.error("No Underwriter Found: Create One Now");
						Underwriter newUw = new Underwriter();
						newUw.setDisplayName(displayName);
						newUw.setImportName(importName);
						newUw.setCreateTs(new Date());
						newUw.setUpdateTs(new Date());
						newUw.setCreateUsername("AutoSetup");
						newUw.setUpdateUsername("AutoSetup");
						newUw.persist();
					}
					
				}
				
				/* Generating Owner Policy Type */
				List<String> ownerPolTypeList=Arrays.asList(((String)setupProps.getProperty("policytypes.constant.owner")).split(","));
				for (String pt: ownerPolTypeList)
				{
					String displayName = pt.split(":")[0];
					String abbrName = pt.split(":")[1];
					
					LOGGER.debug("Owner Policy Type:  "+displayName+":"+abbrName);
					
					//This is where you left off
					
					
					if(PolicyType.findPolicyTypeByDisplayNameAndAbbrName(displayName, abbrName) == null)
					{
						PolicyType newPt = new PolicyType();
						newPt.setDisplayName(displayName);
						newPt.setAbbrName(abbrName);
						newPt.setCreateTs(new Date());
						newPt.setUpdateTs(new Date());
						newPt.setCreateUsername("AutoSetup");
						newPt.setUpdateUsername("AutoSetup");
						newPt.persist();
					}

				}
				
				
				/* Generating Loan Policy Type */
				List<String> loanPolTypeList=Arrays.asList(((String)setupProps.getProperty("policytypes.constant.loan")).split(","));
				for (String pt: loanPolTypeList)
				{
					String displayName = pt.split(":")[0];
					String abbrName = pt.split(":")[1];
					
					LOGGER.debug("Loan Policy Type:  "+displayName+":"+abbrName);

					if(PolicyType.findPolicyTypeByDisplayNameAndAbbrName(displayName, abbrName) == null)
					{
						PolicyType newPt = new PolicyType();
						newPt.setDisplayName(displayName);
						newPt.setAbbrName(abbrName);
						newPt.setCreateTs(new Date());
						newPt.setUpdateTs(new Date());
						newPt.setCreateUsername("AutoSetup");
						newPt.setUpdateUsername("AutoSetup");
						newPt.persist();
					}

				}
				
				
				
			}
			
			/*
	    	List<Pool> list = Pool.findAllPools();
	    	if (list.size()<1)
	    	{
	    		insertMockData();
	    	}
	    	*/
	    	
		}
		catch (Exception e)
		{
			LOGGER.error("Exception occurred while setting up applicaiton",e);
		}
	}

	public SchedulerFactoryBean getSchedulerFactory() {
		return schedulerFactory;
	}

	public void setSchedulerFactory(SchedulerFactoryBean schedulerFactory) {
		this.schedulerFactory = schedulerFactory;
	}



}
